package com.catazy.mvvmlib.ext.download

import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.cancel
import kotlinx.coroutines.isActive
import java.util.concurrent.ConcurrentHashMap

/**
 * 作者: Tao
 * 日期: 2024/1/30
 * 时间: 11:10
 * 描述: 下载池管理类
 */
object DownLoadPool {

    //下载域缓存Map
    private val scopeMap: ConcurrentHashMap<String, CoroutineScope> = ConcurrentHashMap()

    //下载位置缓存Map
    private val pathMap: ConcurrentHashMap<String, String> = ConcurrentHashMap()

    //下载监听回调缓存Map
    private val listenerHashMap: ConcurrentHashMap<String, OnDownloadListener> = ConcurrentHashMap()

    /**
     * 添加下载域
     * @param key String
     * @param job CoroutineScope
     */
    fun add(key: String, job: CoroutineScope) {
        if (scopeMap.containsKey(key)) {
            scopeMap[key]?.cancel()
        }
        scopeMap[key] = job
    }

    /**
     * 添加下载监听回调
     * @param key String
     * @param loadListener OnDownloadListener
     */
    fun add(key: String, loadListener: OnDownloadListener) {
        listenerHashMap[key] = loadListener
    }

    /**
     * 添加下载位置
     * @param key String
     * @param path String
     */
    fun add(key: String, path: String) {
        pathMap[key] = path
    }

    /**
     * 移除
     * @param key String
     */
    fun remove(key: String) {
        pause(key)
        scopeMap.remove(key)
        listenerHashMap.remove(key)
        pathMap.remove(key)
        ShareDownLoadUtil.remove(key)
    }

    /**
     * 暂停
     * @param key String
     */
    fun pause(key: String) {
        val scope = scopeMap[key]
        if (scope != null && scope.isActive) {
            scope.cancel()
        }
    }

    /**
     * 移除Scope
     * @param key String
     */
    fun removeScopeSp(key: String) {
        scopeMap.remove(key)
    }

    /**
     * 获取Scope
     * @param key String
     * @return CoroutineScope?
     */
    fun getScopeFromKey(key: String): CoroutineScope? {
        return scopeMap[key]
    }

    /**
     * 获取监听
     * @param key String
     * @return OnDownloadListener?
     */
    fun getListenerFromKey(key: String): OnDownloadListener? {
        return listenerHashMap[key]
    }

    /**
     * 获取下载位置
     * @param key String
     * @return String?
     */
    fun getPathFromKey(key: String): String? {
        return pathMap[key]
    }

    /**
     * 获取监听Map
     * @return ConcurrentHashMap<String, OnDownloadListener>
     */
    fun getListenerMap(): ConcurrentHashMap<String, OnDownloadListener> {
        return listenerHashMap
    }
}